import { _decorator } from 'cc'
import { EnemyManager } from '../../Base/EnemyManager'
import { ENTITY_STATE_ENUM, EVENT_ENUM } from '../../Enums'
import { IEntity } from '../../Levels'
import DataManager from '../../Runtime/DataManager'
import EventManager from '../../Runtime/EventManager'
import { WoodenSkeletonStateMachine } from './WoodenSkeletonStateMachine'
const { ccclass } = _decorator

@ccclass('WoodenSkeletonManager')
export class WoodenSkeletonManager extends EnemyManager {

  async init(params: IEntity) {
    // 初始化状态机
    this.fsm = this.addComponent(WoodenSkeletonStateMachine)
    await this.fsm.init()
    super.init(params)
    // 监听玩家移动结束事件，是否需要攻击
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack, this)

  }

  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onAttack)
  }

  // 是否攻击
  onAttack() {
    if(this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) return

    const { x: playerX, y: playerY,state: playerState } = DataManager.Instance.player
    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)
    // 在攻击范围内，并且玩家不是死亡状态才攻击
    if(
      (this.x === playerX && disY <= 1 ||
      this.y === playerY && disX <= 1) &&
      playerState !== ENTITY_STATE_ENUM.DEATH &&
      playerState !== ENTITY_STATE_ENUM.AIR_DEATH
    ) {
      this.state = ENTITY_STATE_ENUM.ATTACK
      EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER,ENTITY_STATE_ENUM.DEATH)
    } else {
      this.state = ENTITY_STATE_ENUM.IDLE
    }
  }

}
